﻿/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" />

Type.registerNamespace('TinyMCEExtender');

TinyMCEExtender.TinyMCEBehavior = function(element) {
    TinyMCEExtender.TinyMCEBehavior.initializeBase(this, [element]);

    this._postBackPending = null;
    this._pageLoadingHandler = null;
}
TinyMCEExtender.TinyMCEBehavior.prototype = {
    initialize: function() {
        TinyMCEExtender.TinyMCEBehavior.callBaseMethod(this, 'initialize');

        this.registerPartialUpdateEvents();
        this._pageLoadingHandler = Function.createDelegate(this, this._pageLoading);
        this._pageRequestManager.add_pageLoading(this._pageLoadingHandler);

        var element = this.get_element();
        if (tinyMCE.getInstanceById(element.id) == null || tinyMCE.getInstanceById(element.id) == "undefined")
            tinyMCE.execCommand('mceAddControl', false, element.id);
    },

    dispose: function() {
        if (this._pageRequestManager && this._pageLoadingHandler) {
            this._pageRequestManager.remove_pageLoading(this._pageLoadingHandler);
            this._pageLoadingHandler = null;
        }
        TinyMCEExtender.TinyMCEBehavior.callBaseMethod(this, 'dispose');
    },
    _partialUpdateBeginRequest: function(sender, beginRequestEventArgs) {
        TinyMCEExtender.TinyMCEBehavior.callBaseMethod(this, '_partialUpdateBeginRequest', [sender, beginRequestEventArgs]);
        if (!this._postBackPending) {
            this._postBackPending = true;
        }
    },
    _pageLoading: function(sender, args) {
        if (this._postBackPending) {
            this._postBackPending = false;

            var element = this.get_element();
            var panels = args.get_panelsUpdating();
            for (var i = 0; i < panels.length; i++) {
                var el = element;
                while (el != null) {
                    if (el == panels[i]) break;
                    el = el.parentNode;
                }
                if (el != null) {
                    if (tinyMCE.getInstanceById(element.id) != null && tinyMCE.getInstanceById(element.id) != "undefined") {
                        tinyMCE.execCommand('mceFocus', false, element.id);
                        tinyMCE.execCommand('mceRemoveControl', false, element.id);
                    }
                    break;
                }
            }
        }
    }
}
TinyMCEExtender.TinyMCEBehavior.registerClass('TinyMCEExtender.TinyMCEBehavior', AjaxControlToolkit.BehaviorBase);